/**
 * 统一封装非大模型的异步请求：
 */
import {  message as msg  } from 'ant-design-vue';
//todo: 前期示例，先别管权限及其拦截器，后期再做
//import useStore from '@/store'
import axios from 'axios'
import {localStorage} from '@/utils/storage'
import {isEmpty, isExternal} from '@/utils/quickTool'
let contextPath = import.meta.env.VITE_API_URL
const tokenKey = import.meta.env.VITE_TOKEN_KEY
const refreshKey = import.meta.env.VITE_REFRESH_KEY

class AjaxRequest {

    public request(reqUrl:string,reqData:any={}, reqType = 'json',method:string='POST',hideTips:boolean=false) {

        //兼容问题
        if(isEmpty(Promise.prototype.finally)) {
            Promise.prototype.finally = function (callback) {
                let Promise = this.constructor
                return this.then(
                    (value)=> {
                        // @ts-ignore
                        Promise.resolve(callback()).then(
                            ()=>{ return value }
                        )
                    },
                    (reason)=> {
                        // @ts-ignore
                        Promise.resolve(callback()).then(
                            ()=> { throw reason }
                        )
                    }
                )
            }
        }
        return new Promise((resolve, reject)=>{
            if('http:' == document.location.protocol){   //http协议
                contextPath = contextPath.replace(/^https/,"http")
            }
            //请求头部、请求参数
            let headers:any = {}, params:any
            if (reqType == "json" || reqType == "export") {
                headers["Content-Type"] = "application/json;charset=UTF-8";
                params = JSON.stringify(reqData);
            } else {
                headers["Content-Type"] = "application/x-www-form-urlencoded;charset=UTF-8";
                if(method.toLowerCase()!=='post'||method.toLowerCase()!=='put'){
                    params = new URLSearchParams();
                    if (reqData !== null && typeof reqData === 'object' ) {
                        Object.keys(reqData).forEach((key:string) => {
                            params.append(key, reqData[key]);
                        });
                    }
                }else{
                    params = reqData;
                }

            }
            headers['X-Requested-With'] = 'XMLHttpRequest'

            // 将可能的token放到请求header中，以适应微信小程序、微信浏览器等前端环境
            // let accessToken = localStorage.get(tokenKey)
            // if(!isEmpty(accessToken) && accessToken !== 'null'){
            //     headers[tokenKey] = accessToken
            // }

            axios({
                method: method,
                url: isExternal(reqUrl)? reqUrl: contextPath + reqUrl,
                data:params,
                headers:headers,
                responseType: reqType == "export"? 'blob':undefined,
            }).then( async (response) => {
                // 将可能的token放从响应header中获取，以适应微信小程序、微信浏览器等前端环境
                const accessToken = response.headers[tokenKey.toLowerCase()];
                const refreshToken = response.headers[refreshKey.toLowerCase()];
                if(!isEmpty(accessToken)){ localStorage.set(tokenKey,accessToken) }
                if(!isEmpty(refreshToken)){ localStorage.set(refreshKey,refreshToken) }

                if (reqType == "export") { //对导出文件的处理
                    const url = window.URL.createObjectURL(new Blob([response.data]))
                    const link = document.createElement("a")
                    link.href = url
                    //解析文件名
                    let filename = response.headers["file-download-name"] as string
                    link.download = decodeURI(filename);
                    document.body.appendChild(link)
                    link.click()
                    document.body.removeChild(link) //下载完成移除元素
                    window.URL.revokeObjectURL(url) //释放掉blob对象

                    resolve(filename)
                } else {
                    const {code = null, message = null} = response.data
                    if (code > 1) {
                        if (!hideTips)
                            msg.error(code || message ? code + ": " + message : '系统出错',2)
                        reject({code: code, message: message})
                    } else {
                        if (response.data instanceof ArrayBuffer) { //如果是响应数据为二进制流处理(Excel导出)，则不可以输入日志
                            resolve(response)
                        } else {
                            //console.log('response', response)
                            resolve(response.data)
                        }
                    }
                }

            }).catch( (error)=> {
                console.log('error',error)
                let status=200
                let showMsg = ""
                // 【务必注意】这里的error输出的不是一个对象【error.response才是一个对象】
                if (error.response) {
                    status = error.response.status
                    console.log(status+' error.response.data',error.response.data)
                    console.log(status+' error.response.status',error.response.status)
                    console.log(status+' error.response.headers',error.response.headers)
                    // 请求成功发出且服务器也响应了状态码，但状态代码超出了 2xx 的范围

                } else if (error.request) {
                    // 请求已经成功发起，但没有收到响应
                    console.log('502 error.request',error.request)
                    status = 502
                } else {
                    // 发送请求时出了点问题
                    console.log('501 error.message', error.message)
                    status = 501
                }
                console.log('error.config',error.config)


                if(401 == status){
                    showMsg = "401 未登陆"
                } else if(403 == status){
                    showMsg = "403 您没有访问权限"
                } else if(404 == status){
                    showMsg = "404 请求不存在"
                } else if(400 == status){
                    showMsg = "400服务器无法解析参数"
                } else if(500 == status){
                    showMsg = "500 服务器异常"
                } else if(502 == status){
                    showMsg = "502 服务不可用"
                } else if(504 == status){
                    showMsg = "504 服务器响应超时"
                } else{
                    showMsg = "无效的请求: "+error.message
                }

                if(401 === status || 502 === status) {
                    msg.error('当前页面已失效，请重新登录',2).then(()=>{
                        reject({
                            response:{code:status,message:showMsg}
                        })
                    })
                }else{
                    if(!hideTips)
                        msg.error(reqUrl + " : " + showMsg,2)
                    reject({
                        response:{code:status,message:showMsg}
                    })
                }
            })
        })
    }
}
const Ajax = new AjaxRequest();
export default Ajax